<?php

namespace App\Http\Middleware;

use App\Models\Adminer\Admins;
use App\Models\Smember;
use App\Models\YoServer\Members;
use App\Utils\RedisKeys;
use App\Utils\RedisUtil;
use App\Utils\ResUtil;
use Closure;

class ApiRate
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $api, $expire)
    {
       //ps:  'api.rate:driver.pay,5' $api
        $plat = explode('/', request()->path());
        $member = null;
        switch($plat[0]) {
            case 'admin':
                $member = (new Admins)->currentAdminer();
            break;
            case 'user-side':
                $member = Admins::apiCurrent();
            break;
        }
        if (!$member) {
            return $next($request);
        }
        $key = RedisKeys::API_RATE_LIMIT_PRE . $api . ':' . $member->id;
        if (RedisUtil::get($key) == 1){
            RedisUtil::set($key, 1, $expire);
            return response()->json(ResUtil::error('手速太快，稍后回来'));
        }
        RedisUtil::set($key, 1, $expire);
        return $next($request);
    }
}
